const app = getApp();
const Controller = require('../../controllers/controllers').controller
const util = require('../../../utils/util.js')

const SEQUENCE_MODE = 1//列表循环
const RANDOM_MOD = 2//随机循环
const SINGLE_CYCLE_MOD = 3 // 单曲循环
const manage = wx.getBackgroundAudioManager()

Component({
  properties: {
    title:{
      type:String,
      value:""
    },
    
  },
  /**
   * 组件的初始数据
   */
  data: {
    lyricstarttime:'',
    wordstime:0,
    lyriccurrent: 0,
    lyricmultiple: 1,
    lyricchange: false,
    setInter: null,
    lyricTop: 0,
    lyric:[],
    LyricItemHeight:30,
    currentTime: 0,
    playurl: '',
    currentLyric: null,
    currentLineNum: 0,
    toLineNum:0,
    currentSong: null,
    playMod: app.globalData.playMod,
    closetime: [{
        name: '1分钟后自动关闭',
        value: 60
      },
      {
        name: '5分钟后自动关闭',
        value: 300
      },
      {
        name: '10分钟后自动关闭',
        value: 600
      },
      {
        name: '15分钟后自动关闭',
        value: 900
      },
      {
        name: '20分钟后自动关闭',
        value: 1200
      },
      {
        name: '30分钟后自动关闭',
        value: 1800
      },
      {
        name: '35分钟后自动关闭',
        value: 2100
      }
    ],
    closetimecurrent: 0,
    closetimeend: false,
    percent: 0,
  },
  ready:function(){
    
  },
  /**
   * 组件的方法列表
   */
  methods: {
    //初始化
    _init() {
      let currentIndex = app.globalData.currentIndex || 0;
      let songslist = (app.globalData.songlist.length && app.globalData.songlist)
      let currentSong = app.globalData.songlist[app.globalData.currentIndex] || (songslist && songslist[app.globalData.currentIndex])
      let duration = currentSong && currentSong.duration
      this.setData({
        currentSong: currentSong,
        duration: duration,
        songslist: songslist,
        currentIndex: currentIndex
      })
      this._getPlayUrl(currentSong)
    },
    // 获取播放地址
    _getPlayUrl(currentSong) {
      const _this = this
      if (currentSong && currentSong.audioUrl) {
        _this._createAudio(currentSong)
      } else {
        wx.showToast({
          title: '本歌曲暂时不能播放。请切换下一首',
          icon: 'none'
        })
      }
    },
    // 创建播放器
    _createAudio(currentSong) {
      wx.playBackgroundAudio({
        dataUrl: currentSong.audioUrl,
        title: currentSong.title,
        coverImgUrl: currentSong.imgUrl
      })


      // 监听音乐播放。
      wx.onBackgroundAudioPlay(() => {
        this.setData({
          play: 2,
        })

        app.currentSong = currentSong
        app.play(currentSong.id)

      })
      // 监听音乐暂停。
      wx.onBackgroundAudioPause(() => {
        this.setData({
          play: 1,
        })

        // 更新收听时长接口
        Controller.uploadListenTimes({
          seconds: parseInt(this.data.currentTime)
        })
        .then(res => {

        })
      })
      // 监听音乐停止。
      wx.onBackgroundAudioStop(() => {
        // 更新收听时长接口
        Controller.uploadListenTimes({
          seconds: parseInt(this.data.currentTime)
        })
        .then(res => {

        })
        if (this.data.playMod === SINGLE_CYCLE_MOD) {
          this._init()
          return
        }
        this.next()
      })
      this.onTimeUpdate()
    },
    onTimeUpdate(time) {
      // 监听播放拿取播放进度
      manage.onTimeUpdate(() => {
        const currentTime = manage.currentTime;
        const duration = manage.duration
        this.setData({
          currentTime: this._formatTime(currentTime),
          duration: this._formatTime(duration),
          percent: currentTime / duration * 100
        })
        this.triggerEvent('playstatus2',this.data)
        // if (this.data.lyric.length>0) {
        //   if(currentTime<=0){
        //     this.handleLyric(0)
        //     this.setData({
        //       lineNum:0
        //     })
        //   }else{
        //     this.handleLyric(currentTime)
        //   }
          
        // }
      })
    },
    // 滑动
    musicchange(e) {
      var current = Number(e.detail.value);
      var duration = this._formatSecod(this.data.duration) || 0;
      var max = 506
      var change = '';
      change = current / max * duration;
      manage.seek(change);
    },
    _formatSecod(time) {
      time = time || 0
      if (typeof time == 'string') {
        var min = time.split(':')[0];
        var sec = time.split(':')[1];
        var s = Number(min * 60) + Number(sec);
      }
      return s
    },

    _formatTime(interval) {
      interval = interval | 0
      const minute = interval / 60 | 0
      const second = this._pad(interval % 60)
      return `${minute}:${second}`
    },
    /*秒前边加0*/
    _pad(num, n = 2) {
      let len = num.toString().length
      while (len < n) {
        num = '0' + num
        len++
      }
      return num
    },
    changeMod() {
      let playMod = this.data.playMod + 1
      if (playMod > SINGLE_CYCLE_MOD) {
        playMod = SEQUENCE_MODE
      }
      this.setData({
        playMod: playMod
      })
      this.triggerEvent('playstatus',this.data)
    },
    prev() {

      if(app.globalData.currentIndex!=this.getNextIndex(true)){
        app.globalData.currentIndex = this.getNextIndex(true)
        this._init()
      }
    },
    next() {
      if(app.globalData.currentIndex!=this.getNextIndex(true)){
        app.globalData.currentIndex = this.getNextIndex(true)
        this._init()
      }
      
    },
    // 下一首歌曲的id
    getNextIndex(nextFlag) {
      let ret,
        currentIndex = Number(app.globalData.currentIndex),
        mod = this.data.playMod,
        len = this.data.songslist.length || 1
        // 随机
      if (mod === RANDOM_MOD) {
        ret = util.randomNum(len)
      } else {
        // 下一首
        if (nextFlag) {
          ret = currentIndex + 1 == len ? 0 : currentIndex + 1
        } else {
          ret = currentIndex - 1 < 0 ? len - 1 : currentIndex - 1
        }
      }
      return ret
    },
    // 音乐播放开关
    togglePlaying() {
      // 获取后台音乐播放状态
      var that=this;
      if(manage.src){
        wx.getBackgroundAudioPlayerState({
          success(res) {
            var status = res.status
            let play = 1
            if (status == 1) {
              wx.pauseBackgroundAudio()
              play = 1
            } else {
              wx.playBackgroundAudio()
              play = 2
            }
            that.setData({
              play:play
            })
            that.triggerEvent('playstatus',that.data)
          }
        })
      }else{
        that._init();
      }
      that.selectComponent('#Footer').playmusic();
    },

    playthis(e) {
      const index = e.currentTarget.dataset.index
      app.globalData.currentIndex = index
      this._init()
    },

    bindPickerChange: function (e) {
      var that = this;
      clearInterval(that.data.setInter)
      var index = e.detail.value;
      var time = this.data.closetime[index].value;

      wx.showToast({
        title: this.data.closetime[index].name,
        icon: "none"
      })
      that.data.setInter = setInterval(res => {
        time--;
        that.setData({
          closetimecurrent: that._formatTime(time),
        })
        if (time <= 0) {
          clearInterval(that.data.setInter)
          that.setData({
            closetimeend: true,
            settimebool: false,
            play: 1,
            setInter:that.data.setInter
          })

          manage.pause()
        }
      }, 1000)
      this.setData({
        settimebool: true,
      })
      that.triggerEvent('playstatus',this.data)
    },
    // 获取歌词
    _getLyric(currentSong) {
      var that=this;
      if (currentSong.words) {
        var lyric = ''
        if (typeof currentSong.words == 'string') {
          lyric = JSON.parse(currentSong.words);
        } else {
          lyric = currentSong.words;
        }

        for (let item of lyric) {
          item.time = that._formatSecod(item.time) || ''
        }
        that.setData({
          lyric: lyric
        })
      } else {
        that.setData({
          lyric: []
        })
      }
      that.triggerEvent('playstatus',this.data)
    },

    isJSON(str) {
      if (typeof str == 'string') {
        try {
          var obj = JSON.parse(str);
          if (typeof obj == 'object' && obj) {
            return true;
          } else {
            return false;
          }
        } catch (e) {
          return false;
        }
      }
    },
    // 歌词滚动回调函数
    handleLyric(currentTime) {
      if(this.data.lyricchange){
        return
      }
      let lines = [{
          time: 0,
          txt: ''
        }],
        lyric = this.data.lyric,
        lineNum
      lines = lines.concat(lyric)
      for (let i = 0; i < lines.length; i++) {
        if (i < lines.length - 1) {
          let time1 = lines[i].time,
            time2 = lines[i + 1].time
          if (currentTime > time1 && currentTime < time2) {
            lineNum = i - 1
            break;
          }
        } else {
          lineNum = lines.length - 2

        }
      }
      this.setData({
        currentLineNum: lineNum
      })
      
      let toLineNum = lineNum - 3
      if (lineNum > 3 && toLineNum != this.data.toLineNum) {
        this.setData({
          toLineNum: toLineNum<=0?0:toLineNum
        })
      }else{
        if(this._formatSecod(this.data.currentTime)<=0.1){
          this.setData({
            toLineNum: 0,
            lyricTop:0
          })
        }
      }
      that.triggerEvent('playstatus',this.data)
    },
    lyricscroll(e) {
      if (this.data.lyricchange) {
        var index = Math.round(e.detail.scrollTop / this.data.LyricItemHeight);
        var time = this.data.lyric[index+3].time
        if (time != this.data.wordstime) {
          this.setData({
            wordstime: time
          })
        }
      }
    },
    lyricstart(e) {
      var that=this;
      that.data.lyricstarttime=setTimeout(res=>{
        that.setData({
          lyricchange: true
        })
        manage.pause()
      },100)
      
    },
    lyricend(e) {
      
      var that = this

      setTimeout(res => {
        that.setData({
          lyricchange: false,
        })
        clearTimeout(that.data.lyricstarttime)
        manage.play()
        manage.seek((that.data.wordstime || 0));
      })
    },
    // playstatus(){
    //   this.triggerEvent('playstatus',this.data)
    // },
  }
})
